//
//  RMMPayOrderViewController.m
//  Romomo
//
//  Created by puman on 16/10/17.
//  Copyright © 2016年 mazegong. All rights reserved.
//

#import "RMMPayOrderViewController.h"
#import "RMMPayOrderTableViewCell.h"
#import "RMMHuiYuanKaPayTableViewCell.h"
#import "RMMChongZhiViewController.h"
#import "RMMMemberCardViewController.h"
#import <PassKit/PassKit.h>
#import <PassKit/PKPaymentAuthorizationViewController.h>
#import <AddressBook/AddressBook.h>
#import "RMMOrderDetailsViewController.h"
#import "RMMShopingModel.h"
#import "RMMOrderModel.h"
#import "RMMPayJieGuoViewController.h"
#import <LocalAuthentication/LocalAuthentication.h>
#import "MZGPasswordView.h"
#import "RMMMoneyShareView.h"
#import "RMMHomeShareView.h"

@interface RMMPayOrderViewController ()<UITableViewDelegate, UITableViewDataSource>

@end

@implementation RMMPayOrderViewController
{
    UITableView *_tableView;
    RMMPayFailureView *_backView;
    RMMPayResultView *_resultView;
    RMMNotNetWorkView *_networkView;
    RMMHomeShareView *_shareVIew;
    RMMMoneyShareView *_moneyShareView;
    UIBarButtonItem *_item;
    NSArray *_imageNameArr;
    NSArray *_titleArr;
    UIButton *_bottomBut;
    NSMutableDictionary *_statDic;
    NSMutableArray *summaryItems;
    NSMutableArray *shippingMethods;
    NSString *_order_no;
    BOOL _isSuccess;
    MZGPasswordView *_passwordView;
    NSString *_pay_way_code;
    NSString *_objName;
    NSString *_huiYuanKaMoney;
    NSString *_price;
    NSString *_memberCardYouHuiMoney;
    NSDictionary *_moneyDic;
    NSString *_balance; // 会员卡余额
    NSString *_yuE;
    NSString *_titleName;
    NSString *_desTitleName;
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    _backView.hidden = YES;
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self getMemberBalance];
}
- (void)dealloc {
    NS_REM(@"PAYJIEGUOFUWU", [RMMFileManager shareHandle].payTypeName);
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"支付订单";
    self.view.backgroundColor = kWhiteColor;
    [self addViews];
    if ([_type isEqualToString:@"打赏"]) {
        [self getMemberBalance];
    } else {
        [self getData];
    }
    // Do any additional setup after loading the view.
}
- (void)getData{
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    NSString *url = GetDisCountAmtUrl;
    NSString *is_face = [_youHuiDic objectForKey:@"是否使用颜值"];
    NSString *is_youHui = [_youHuiDic objectForKey:@"是否使用优惠券"];
    dic[@"cust_id"] = [RMMFileManager shareHandle].userDic[@"CUST_ID"];
    dic[@"originalprice"] = [RMMFileManager shareHandle].totalPrcie;
    dic[@"is_face"] = is_face;
    dic[@"order_id"] = _dataDic[@"OrderId"];
    dic[@"is_home"] = [RMMFileManager shareHandle].fuWuType;
    if ([is_youHui isEqualToString:@"1"]) {
        NSDictionary *newDic = [_youHuiDic objectForKey:@"优惠券信息"];
        dic[@"voucher_id"] = newDic[@"VOUCHER_ID"];
    }
    [OSRequestManager requestWithUrlString:url parDic:dic network:^(BOOL isNetwork) {
        if (isNetwork) {
            _networkView.hidden = YES;
        } else {
            _networkView.hidden = NO;
        }
    } method:GET finish:^(NSDictionary *dataDic) {
        NSString *status = [NSString stringWithFormat:@"%@",dataDic[@"status"]];
        if ([status isEqualToString:@"1"]) {
            _moneyDic = dataDic[@"data"];
            if ([[_youHuiDic objectForKey:@"总价钱"] floatValue] == 0) {
                _price = @"0";
                [self confirmPay];
            } else {
                CGFloat m1 = 0.00;
                CGFloat m2 = 0.00;
                if ([is_face isEqualToString:@"1"]) {
                    m1 = [dataDic[@"data"][@"FACE_ATM"] floatValue];
                }
                if ([is_youHui isEqualToString:@"1"]) {
                    m2 = [dataDic[@"data"][@"VOUCHER_ATM"] floatValue];
                }
                NSString *t = [RMMFileManager shareHandle].totalPrcie;
                CGFloat m3 = [dataDic[@"data"][@"VIP_ATM"] floatValue];
                _memberCardYouHuiMoney = [NSString stringWithFormat:@"%.2f",[dataDic[@"data"][@"VIP_ATM"] floatValue]];
                CGFloat s1 = [t floatValue] - m3 - m1 - m2;
                if (s1 < 0) {
                    CGFloat y = [[_youHuiDic objectForKey:@"颜值"] floatValue];
                    if ([t floatValue] - m3 - m2 < 0) {
                        [_youHuiDic setValue:@"0" forKey:@"是否使用颜值"];
                        [_youHuiDic setValue:@"0" forKey:@"颜值"];
                    } else {
                        [_youHuiDic setValue:[NSString stringWithFormat:@"%.2f",y + s1] forKey:@"颜值"];
                    }
                    _huiYuanKaMoney = @"0";
                    _totalPrice = [NSString stringWithFormat:@"%.2f",[t floatValue] - m2 - m1];
                    _price = _totalPrice;
                } else {
                    _huiYuanKaMoney = [NSString stringWithFormat:@"%.2f",[t floatValue] - m3 - m1 - m2];
                    _totalPrice = [NSString stringWithFormat:@"%.2f",[t floatValue] - m2 - m1];
                    _price = _totalPrice;
                }
                [self getMemberBalance];
            }
        } else {
            [RMMFileManager MBProgressWith:dataDic[@"message"] onView:self.view];
        }
        [_tableView reloadData];

    } error:^(NSError *errors) {
        
    } view:self.view];
}
//  会员卡余额
- (void)getMemberBalance{
    NSMutableDictionary *parDic = [NSMutableDictionary dictionary];
    NSString *cust_id = [RMMFileManager retrunObjWith:[RMMFileManager shareHandle].userDic[@"CUST_ID"]];
    parDic[@"cust_id"] = cust_id;
    parDic[@"org_no"] = Org_no;
    NSString *url = GetCustCardUrl;
    [OSRequestManager requestWithUrlString:url parDic:parDic network:^(BOOL isNetwork) {
        if (isNetwork) {
            _networkView.hidden = YES;
        } else {
            _networkView.hidden = NO;
        }
    } method:GET finish:^(NSDictionary *dataDic) {
        NSString *status = [NSString stringWithFormat:@"%@",dataDic[@"status"]];
        if ([status isEqualToString:@"1"]) {
            _balance = [NSString stringWithFormat:@"%.2f",[dataDic[@"data"][@"BALANCE"] floatValue]];
            _yuE = [NSString stringWithFormat:@"%@元", _balance];
        } else {
            [RMMFileManager MBProgressWith:dataDic[@"message"] onView:self.view];
        }
        [_tableView reloadData];
    } error:^(NSError *errors) {
        
    } view:self.view];

}
- (void)addViews{
    _yuE = @"0";
    _price = @"0";
    [self addLeftItem];
    _order_no = _dataDic[@"OrderNo"];
    _memberCardYouHuiMoney = @"";
    _statDic = [NSMutableDictionary dictionary];
    _imageNameArr = @[@"微信支付@3x",@"支付宝@3x"];
    _titleArr = @[@"微信支付",@"支付宝支付"];
//    if( [[[UIDevice currentDevice] systemVersion] floatValue] < 9.2){
//        _imageNameArr = @[@"朋友代付@2x",@"微信支付@2x",@"支付宝@2x"];
//        _titleArr = @[@"找朋友代付",@"微信支付",@"支付宝支付"];
//    }
    _isSuccess = YES;
    UIView *footView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWideth, 0)];
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWideth, kScreenHeight - 64 - 49) style:(UITableViewStylePlain)];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    _tableView.tableFooterView = footView;
    [_tableView registerClass:[RMMHuiYuanKaPayTableViewCell class] forCellReuseIdentifier:@"Cell"];
    [_tableView registerClass:[RMMPayOrderTableViewCell class] forCellReuseIdentifier:@"PayCell"];

    [self.view addSubview:_tableView];
    [self addBottomView];
    if ([_type isEqualToString:@"打赏"]) {
        _price = _totalPrice;
    }
    _backView = [[RMMPayFailureView alloc] initWithFrame:CGRectMake(0, 0, kScreenWideth, kScreenHeight - 64)];
    BUTTON_S(_backView.backHomeBut, backHomeButClick:);
    BUTTON_S(_backView.goonPayBut, backHomeButClick:);
    _backView.hidden = YES;
    [self.view addSubview:_backView];
    
    _resultView = [[RMMPayResultView alloc] initWithFrame:CGRectMake(0, 0, kScreenWideth, kScreenHeight - 64)];
    _resultView.hidden = YES;
    BUTTON_S(_resultView.doneBut, doneButClick);
    [self.view addSubview:_resultView];
    
    _passwordView = [[MZGPasswordView alloc] initWithFrame:CGRectMake(0, 0, kScreenWideth, kScreenHeight - 64)];
    _passwordView.hidden = YES;
     [self.view addSubview:_passwordView];
    
    _networkView = [[RMMNotNetWorkView alloc] initWithFrame:CGRectMake(0, 0, kScreenWideth, kScreenHeight - 64)];
    _networkView.hidden = YES;
    BUTTON_S(_networkView.button, networkBut);
    [self.view addSubview:_networkView];
    
    _moneyShareView = [[RMMMoneyShareView alloc] initWithFrame:CGRectMake(0, 0, kScreenWideth, kScreenHeight)];
    [self.view addSubview:_moneyShareView];
    _moneyShareView.hidden = YES;
    BUTTON_S(_moneyShareView.button, moneyBut);
    
    _shareVIew = [[RMMHomeShareView alloc] initWithFrame:CGRectMake(0, 0, kScreenWideth, kScreenHeight)];
    _shareVIew.hidden = YES;
    UIWindow *widow = [UIApplication sharedApplication].keyWindow;
    [widow addSubview:_shareVIew];
    // 分享按钮
    for (int i = 0; i < 5; i++) {
        UIButton *button = [_shareVIew viewWithTag:50 + i];
        BUTTON_S(button, shareButtonClick:);
    }
}
// 支付成功后分享红包
- (void)moneyBut{
    _moneyShareView.hidden = YES;
    _shareVIew.hidden = NO ;
    [UIView animateWithDuration:kInterval animations:^{
        _shareVIew.view.frame = CGRectMake(0, kScreenHeight - 230, kScreenWideth, 230);
        _shareVIew.backView.alpha = 1;
    } completion:^(BOOL finished) {
        
    }];
}
// 分享
- (void)shareButtonClick:(UIButton *)button{
    [UIView animateWithDuration:kInterval animations:^{
        _shareVIew.view.frame = CGRectMake(0, kScreenHeight, kScreenWideth, 230);
        _shareVIew.backView.alpha = 0.0;
    } completion:^(BOOL finished) {
        _shareVIew.hidden = YES;
    }];
    NSArray *array = @[@(UMSocialPlatformType_WechatSession),@(UMSocialPlatformType_WechatTimeLine),@(UMSocialPlatformType_QQ),@(UMSocialPlatformType_Sina),@(UMSocialPlatformType_Qzone)];
    
    UMSocialPlatformType platformType = - 8;
    platformType = [array[button.tag - 50] integerValue];
    UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
    if (button.tag == 53) {
        // UMShareImageObject *shareObject = [[UMShareImageObject alloc] init];
        // shareObject.thumbImage = [UIImage imageNamed:@"Icon-iPhone-60@2x"];
        messageObject.text = [NSString stringWithFormat:@"http://ydywx.puman.cn/Web/RedBag/SendRedBag.ashx?action=RedShow&order_id=%@&type=0",_dataDic[@"OrderId"]];
        // messageObject.shareObject = shareObject;
    } else {
        UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:_titleName.length ? _titleName : @"容么么" descr:_desTitleName.length ? _desTitleName : @"亲爱的小主,容么么为你献上红包一枚!" thumImage:[UIImage imageNamed:@"Icon-iPhone-60@3x"]];
        //设置网页地址
        shareObject.webpageUrl = [NSString stringWithFormat:@"http://ydywx.puman.cn/Web/RedBag/SendRedBag.ashx?action=RedShow&order_id=%@&type=0",_dataDic[@"OrderId"]];
        messageObject.shareObject = shareObject;
    }
    [[UMSocialManager defaultManager] shareToPlatform:platformType messageObject:messageObject currentViewController:nil completion:^(id result, NSError *error) {
        
    }];
}
- (void)networkBut{
    [self getData];
}

- (void)addLeftItem{
    _item = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:(UIBarButtonItemStylePlain) target:self action:@selector(cancel)];
    self.navigationItem.leftBarButtonItem = _item;
    //_item.tintColor = COLORFROMCODE(0x9B9B9B1, 1);
    
}
- (void)cancel{
    [self.navigationController popViewControllerAnimated:YES];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 1) {
        return _titleArr.count;
    }
    return 1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        return 100;
    }
    return 60;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWideth, 100)];
        view.backgroundColor = RGBA(245, 246, 247, 1);
        
        UIView *viewA = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWideth, 70)];
        viewA.backgroundColor = kWhiteColor;
        [view addSubview:viewA];
        
        UILabel *labelA = [[UILabel alloc] initWithFrame:CGRectMake(15, 0, 80, 70)];
        labelA.text = @"应付金额";
        labelA.font = kFont(13);
        labelA.textColor = COLORFROMCODE(0x2C2C2C, 1);
        [viewA addSubview:labelA];
        
        UILabel *labelB = [[UILabel alloc] initWithFrame:CGRectMake(labelA.right, 0, kScreenWideth - 15 -labelA.right, 70)];
        labelB.text = [NSString stringWithFormat:@"¥%@",_price];
        labelB.font = kFont(24);
        labelB.textAlignment = NSTextAlignmentRight;
        labelB.textColor = COLORFROMCODE(0x303137, 1);
        [viewA addSubview:labelB];
        
        UILabel *labelC = [[UILabel alloc] initWithFrame:CGRectMake(15, labelA.bottom, 100, 30)];
        labelC.text = @"推荐支付方式";
        labelC.font = kFont(13);
        labelC.textColor = COLORFROMCODE(0x9B9B9B1, 1);
        [view addSubview:labelC];

        UILabel *labelD = [[UILabel alloc] initWithFrame:CGRectMake(labelC.right, labelC.top, kScreenWideth - labelC.right - 15, 30)];
        labelD.text = @"活动仅限单点项目";
        labelD.font = kFont(13);
        labelD.textColor = kBasicColor;
        labelD.textAlignment = NSTextAlignmentRight;
        [view addSubview:labelD];

        return view;
    } else {
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWideth, 30)];
        view.backgroundColor = RGBA(245, 246, 247, 1);
        UILabel *labelA = [[UILabel alloc] initWithFrame:CGRectMake(15, 0, kScreenWideth - 30, 30)];
        labelA.text = @"其他支付方式";
        labelA.font = kFont(13);
        labelA.textColor = COLORFROMCODE(0x9B9B9B1, 1);
        [view addSubview:labelA];
        return view;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return 100;
    }
    return 30;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        RMMHuiYuanKaPayTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
        BUTTON_S(cell.chongZhiBut, chongZhiButClick);
        BUTTON_S(cell.selcetBut, carSelcetBut:);
        cell.selcetBut.tag = 2;
        cell.string = _memberCardYouHuiMoney;
        cell.balance = _yuE;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;

    } else {
        RMMPayOrderTableViewCell *cell =[tableView dequeueReusableCellWithIdentifier:@"PayCell"];
        cell.imageName = _imageNameArr[indexPath.row];
        cell.titleName = _titleArr[indexPath.row];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
       // BUTTON_S(cell.selcetBut, selcetButPayType:);
        cell.selcetBut.userInteractionEnabled = NO;
        cell.selcetBut.tag = 3 + indexPath.row;
        return cell;
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        RMMMemberCardViewController *VC = [[RMMMemberCardViewController alloc] init];
        [self.navigationController pushViewController:VC animated:YES];
    } else {
        [self selcetButPayType:indexPath.row];
    }
}
// 去充值
- (void)chongZhiButClick{
    RMMChongZhiViewController *VC = [[RMMChongZhiViewController alloc] init];
    VC.balance = _balance;
    [self.navigationController pushViewController:VC animated:YES]; 
}
// 选择支付方式
- (void)selcetButPayType:(NSInteger)row{
    UIButton *but = [self.view viewWithTag:2];
    UIButton *button = [self.view viewWithTag:row + 3];
    [_statDic setObject:@0 forKey:[NSNumber numberWithInteger:but.tag]];
    [but setImage:[UIImage imageNamed:@"不可选@3x"] forState:(UIControlStateNormal)];
    NSNumber *stat = [_statDic objectForKey:[NSNumber numberWithInteger:button.tag]];
    for (int i = 0; i < _titleArr.count; i++) {
        UIButton *buttons = [self.view viewWithTag:3 + i];
        if (buttons.tag ==button.tag) {
            if ([stat isEqualToNumber:@1]) {
                [_statDic setObject:@0 forKey:[NSNumber numberWithInteger:button.tag]];
                [button setImage:[UIImage imageNamed:@"可选@3x"] forState:(UIControlStateNormal)];
                [self cannotPay];
            } else {
                [_statDic setObject:@1 forKey:[NSNumber numberWithInteger:button.tag]];
                [button setImage:[UIImage imageNamed:@"选中@3x"] forState:(UIControlStateNormal)];
                [self canPay];
            }

        } else {
            [buttons setImage:[UIImage imageNamed:@"可选@3x"] forState:(UIControlStateNormal)];
            [_statDic setObject:@0 forKey:[NSNumber numberWithInteger:buttons.tag]];
        }
    }
    _price = _totalPrice;
    [_tableView reloadData];
}
- (void)carSelcetBut:(UIButton *)button{
    NSNumber *stat = [_statDic objectForKey:[NSNumber numberWithInteger:button.tag]];
    if ([stat isEqualToNumber:@1]) {
        [_statDic setObject:@0 forKey:[NSNumber numberWithInteger:button.tag]];
        [button setImage:[UIImage imageNamed:@"不可选@3x"] forState:(UIControlStateNormal)];
        [self cannotPay];

    } else {
        [_statDic setObject:@1 forKey:[NSNumber numberWithInteger:button.tag]];
        [button setImage:[UIImage imageNamed:@"选中@3x"] forState:(UIControlStateNormal)];
        [self canPay];
    }
    for (int i = 0; i < _titleArr.count; i++) {
        UIButton *buttons = [self.view viewWithTag:3+ i];
        [buttons setImage:[UIImage imageNamed:@"可选@3x"] forState:(UIControlStateNormal)];
        [_statDic setObject:@0 forKey:[NSNumber numberWithInteger:buttons.tag]];
    }
    if (![_type isEqualToString:@"打赏"]) {
        _price = _huiYuanKaMoney;
    }
    _yuE = [NSString stringWithFormat:@"%@元",_balance];

    [_tableView reloadData];
}
- (void)addBottomView{
    UIView *bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, kScreenHeight - 49 - 64, kScreenWideth, 49)];
    bottomView.backgroundColor = kWhiteColor;
    [self.view addSubview:bottomView];
    
    UILabel *lineLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, bottomView.width, 0.5)];
    lineLabel.backgroundColor = RGBA(221, 221, 221, 1);
    [bottomView addSubview:lineLabel];
    
    _bottomBut = [UIButton buttonWithType:(UIButtonTypeCustom)];
    _bottomBut.frame = CGRectMake(kScreenWideth / 2 - kHalf * 2, 6.5, 4 * kHalf, 36);
    _bottomBut.backgroundColor = RGBA(237, 238, 239, 1);
    [_bottomBut setTitleColor:RGBA(212, 213, 214, 1) forState:(UIControlStateNormal)];
    _bottomBut.titleLabel.font = kBFont(14);
    _bottomBut.layer.masksToBounds = YES;
    _bottomBut.layer.cornerRadius = 18;
    [_bottomBut setTitle:@"确认支付" forState:(UIControlStateNormal)];
    _bottomBut.userInteractionEnabled = NO;
    BUTTON_S(_bottomBut, confirmPay);
    [bottomView addSubview:_bottomBut];

}
// 可以支付
- (void)canPay{
    _bottomBut.backgroundColor = kBasicColor;
    [_bottomBut setTitleColor:kWhiteColor forState:(UIControlStateNormal)];
     _bottomBut.userInteractionEnabled = YES;
}
// 不可以支付
- (void)cannotPay{
    _bottomBut.backgroundColor = RGBA(237, 238, 239, 1);
    [_bottomBut setTitleColor:RGBA(212, 213, 214, 1) forState:(UIControlStateNormal)];
     _bottomBut.userInteractionEnabled = NO;
}
// 去支付
- (void)confirmPay{
    for (NSNumber *key in _statDic) {
        NSNumber *value = _statDic[key];
        if ([value isEqualToNumber:@1]) {
            if ([key isEqualToNumber:@2]) {
                // 会员卡支付
                _pay_way_code = @"5";
            } else if ([key isEqualToNumber:@6]) {
                // 找朋友代付
                _pay_way_code = @"";
                [RMMFileManager MBProgressWith:@"抱歉,支付方式暂不支持!" onView:self.view];
                return;
            } else if ([key isEqualToNumber:@3]) {
                // 微信支付
                _pay_way_code = @"7";
            } else if ([key isEqualToNumber:@4]) {
                // 支付宝支付
                _pay_way_code = @"8";
            } else {
                return;
            }
        }
    }
    if (_price == 0) {
        _pay_way_code = @"5";
    }
    if ([_type isEqualToString:@"打赏"]) {
        [RMMFileManager shareHandle].payTypeName = @"打赏";
        _order_no = _order_number;
        [self beginPay];
    } else {
        [RMMFileManager shareHandle].payTypeName = @"服务购买";
        NSMutableDictionary *parDic = [NSMutableDictionary dictionary];
        NSString *cust_id = [RMMFileManager retrunObjWith:[RMMFileManager shareHandle].userDic[@"CUST_ID"]];
        parDic[@"org_no"] = Org_no;
        parDic[@"cust_id"] = cust_id;
        parDic[@"order_id"] = _dataDic[@"OrderId"];
        NSDictionary *newDic = [_youHuiDic objectForKey:@"优惠券信息"];
        NSString *is_face = [_youHuiDic objectForKey:@"是否使用颜值"];
        NSString *is_youHui = [_youHuiDic objectForKey:@"是否使用优惠券"];
        if ([is_youHui isEqualToString:@"1"]) {
            parDic[@"voucher_atm"] = _moneyDic[@"VOUCHER_ATM"];
            parDic[@"my_voucher_id"] = newDic[@"VOUCHER_ID"];
        }
        if ([is_face isEqualToString:@"1"]) {
            parDic[@"face_atm"] = [_youHuiDic objectForKey:@"颜值"];
        }
        if ([_pay_way_code isEqualToString:@"5"]) {
            parDic[@"vip_atm"] = _moneyDic[@"VIP_ATM"];
        }
        parDic[@"payment"] = _price;
        if ([_isHome isEqualToString:@"1"]) {
            parDic[@"store_id"] = @"-10";
            parDic[@"adder_id"] = [[RMMFileManager shareHandle].bookingDic objectForKey:@"地址"][@"ID"];
        } else {
            parDic[@"store_id"] = [[RMMFileManager shareHandle].bookingDic objectForKey:@"地址"][@"ID"];
            parDic[@"adder_id"] = @"";
        }
        if ([_price isEqualToString:@"0"]) {
            parDic[@"pay_way_code"] = @"5";
            _pay_way_code = @"5";
        } else {
            parDic[@"pay_way_code"] = _pay_way_code;
        }
        parDic[@"is_home"] = _isHome;
        parDic[@"region_id"] = [RMMFileManager shareHandle].region_id;
        NSDictionary *skillDic = [[RMMFileManager shareHandle].bookingDic objectForKey:@"技师"];
        parDic[@"masseur"] = skillDic[@"EMP_ID"];
        parDic[@"begin_time"] = [[RMMFileManager shareHandle].bookingDic objectForKey:@"时间"];
        parDic[@"long_time"] = [RMMFileManager shareHandle].totalTimeLength;
        parDic[@"who"] = @"0";
        NSString *url = BuyFuWuUrl;
        [OSRequestManager requestWithUrlString:url parDic:parDic method:POST finish:^(NSDictionary *dataDic) {
            NSString *status = [NSString stringWithFormat:@"%@",dataDic[@"status"]];
            if ([status isEqualToString:@"1"]) {
                [self beginPay];
            } else {
                [RMMFileManager MBProgressWith:dataDic[@"message"] onView:self.view];
            }
        } error:^(NSError *errors) {
            
        } view:self.view];
    }
 }
// 指纹识别
- (void)touch_id{
    //1. 判断系统版本
    if ([UIDevice currentDevice].systemVersion.floatValue >= 8.0) {
        //2. LAContext : 本地验证对象上下文
        LAContext *context = [LAContext new];
        context.localizedFallbackTitle = @"输入密码";
        context.localizedCancelTitle = @"取消";
        //3. 判断是否可用
        //Evaluate: 评估  Policy: 策略,方针
        //LAPolicyDeviceOwnerAuthenticationWithBiometrics: 允许设备拥有者使用生物识别技术
        NSError *aotherError = nil;
        NSString *myLocalizedReasonString = @"我需要验证是否是机主本人操作!";
        if ([context canEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics error:&aotherError]) {
            //4. 开始使用指纹识别
            //localizedReason: 指纹识别出现时的提示文字, 一般填写为什么使用指纹识别
            [context evaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics localizedReason:myLocalizedReasonString reply:^(BOOL success, NSError * _Nullable error) {
                
                if (success) {
                    NSLog(@"指纹识别成功");
                } else {
                    switch (error.code) {
                        case LAErrorAuthenticationFailed:
                        {
                            NSLog(@"用户提供的指纹不对");
                        }
                            break;
                        case LAErrorUserCancel:
                        {
                            NSLog(@"用户点击了取消按钮");
                        }
                            break;
                        case LAErrorUserFallback:
                        {
                            NSLog(@"用户选择输入密码");
                            _passwordView.hidden = NO;
                        }
                            break;
                        case LAErrorSystemCancel:
                        {
                            NSLog(@"切换到其他程序了,被系统取消了");
                        }
                            break;
                        case LAErrorTouchIDLockout:
                        {
                            // 输入多次被锁定
                            NSLog(@"用户指纹错误多此,Touch ID被锁定");
                        }
                            break;
                        case LAErrorAppCancel:
                        {
                            NSLog(@"被突如起来的应用打断,比如电话");
                        }
                            break;
                            
                        default:
                            break;
                    }
                }
            }];
            
        } else {
            switch (aotherError.code) {
                case LAErrorPasscodeNotSet:
                {
                    NSLog(@"设置里面没有设置密码");
                }
                    break;
                case LAErrorTouchIDNotAvailable:
                {
                    NSLog(@"设备不支持TouchID");
                }
                    break;
                case LAErrorTouchIDNotEnrolled:
                {
                    NSLog(@"设备里面没有设置Touch ID指纹");
                }
                    break;
                case LAErrorInvalidContext:
                {
                    NSLog(@"创建指纹对象失效");
                }
                    break;
                    
                default:
                    break;
            }
        }
    }
}
- (void)beginPay{
    NSMutableDictionary *parDic = [NSMutableDictionary dictionary];
    parDic[@"order_no"] = _order_no;
    parDic[@"atm"] = _price;
    NSString *url = @"";
    if ([_price floatValue] < 0) {
        [RMMFileManager MBProgressWith:@"金额出现错误!" onView:self.view];
        [self.navigationController popToRootViewControllerAnimated:YES];
        return;
    }
    if ([_pay_way_code isEqualToString:@"5"]) {
        [self paySuccess];
        NS_POST(@"UPDATEMINEDATA", nil, nil);
        return;
    } else if ([_pay_way_code isEqualToString:@"7"]) {
        // 微信支付
        url = WeChatPayUrl;
    } else if ([_pay_way_code isEqualToString:@"8"]) {
        // 支付宝支付
        url = GetALiPaySignUrl;
    } else {
        
    }
    [OSRequestManager requestWithUrlString:url parDic:parDic method:GET finish:^(NSDictionary *dataDic) {
        NSString *status = [NSString stringWithFormat:@"%@",dataDic[@"status"]];
        if ([status isEqualToString:@"1"]) {
            NS_ADD(payJieGuo:, @"PAYJIEGUOFUWU", [RMMFileManager shareHandle].payTypeName);
            if ([_pay_way_code isEqualToString:@"5"]) {
                // 会员卡
            } else if ([_pay_way_code isEqualToString:@"7"]) {
                // 微信
                [self wechatPayWith:dataDic];
            } else if ([_pay_way_code isEqualToString:@"8"]) {
                // 支付宝
                [self aLipayWith:[RMMPayManager backSingWithDic:dataDic[@"data"]]];
            }
        } else {
            [RMMFileManager MBProgressWith:dataDic[@"message"] onView:self.view];
        }
    } error:^(NSError *errors) {
        
    } view:self.view];
}
// 微信支付
- (void)wechatPayWith:(NSDictionary *)dataDic{
    NSDictionary *dic = dataDic[@"data"];
    PayReq *request = [[PayReq alloc] init];
    request.partnerId                 = dic[@"partnerid"];
    request.prepayId                  = dic[@"prepayid"];
    request.package                   = dic[@"package"];
    request.nonceStr                  = dic[@"noncestr"];
    request.sign                      = dic[@"sign"];
    request.timeStamp                 = [dic[@"timestamp"] doubleValue];
    [WXApi sendReq:request];
}
- (void)aLipayWith:(NSString *)sign{
    [[AlipaySDK defaultService] payOrder:sign fromScheme:ALiPaySchemes callback:^(NSDictionary *resultDic) {
        self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:(UIBarButtonItemStylePlain) target:self action:nil];
    }];
}
- (void)payJieGuo:(NSNotification *)notification{
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:(UIBarButtonItemStylePlain) target:self action:nil];
    _objName = notification.object;
    if([notification.object isEqualToString:@"服务购买"]){
        NSDictionary *dic = [notification userInfo];
        if ([_pay_way_code isEqualToString:@"5"]) {
            // 会员卡
        } else if ([_pay_way_code isEqualToString:@"7"]) {
            // 微信
            NSString *type = dic[@"type"];
            if ([type isEqualToString:@"成功"]) {
                [self paySuccess];
            } else {
                [self payFailure];
                _backView.titleName = @"失败";
            }
        } else if ([_pay_way_code isEqualToString:@"8"]) {
            // 支付宝
            NSString *status = dic[@"resultStatus"];
            if ([status isEqualToString:@"9000"]) {
                // 支付成功
                [self paySuccess];
            } else {
                [self payFailure];
                _backView.titleName = dic[@"memo"];
            }

        }
    } else if ([notification.object isEqualToString:@"打赏"]) {
        NSDictionary *dic = [notification userInfo];
        if ([_pay_way_code isEqualToString:@"5"]) {
            // 会员卡
        } else if ([_pay_way_code isEqualToString:@"7"]) {
            // 微信
            NSString *type = dic[@"type"];
            if ([type isEqualToString:@"成功"]) {
                [self paySuccess];
            } else {
                [self payFailure];
                _backView.titleName = @"失败";
            }
        } else if ([_pay_way_code isEqualToString:@"8"]) {
            // 支付宝
            NSString *status = dic[@"resultStatus"];
            if ([status isEqualToString:@"9000"]) {
                // 支付成功
                [self paySuccess];
            } else {
                [self payFailure];
                _backView.titleName = dic[@"memo"];
            }
        }
    }
}
// 支付成功
- (void)paySuccess{
    // 支付成功
    if (_isSuccess) {
        self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:(UIBarButtonItemStylePlain) target:self action:nil];
        _isSuccess = NO;
        _resultView.hidden = NO;
        _resultView.titelName = @"购买服务";
        _resultView.price = _price;
        _backView.hidden = YES;
        self.navigationItem.title = @"支付结果";
        [RMMFileManager shareHandle].thred = @"1";
        NS_POST(@"ORDERUPDATA", nil, nil);
        NS_POST(@"SHOPFRESH", nil, nil);
        [RMMFileManager shareHandle].fromSkillType = @"0";
        [[RMMFileManager shareHandle].bookingDic removeAllObjects];
        if (![_type isEqualToString:@"打赏"]) {
            [self getRedBagTitle];
        }
    }
}
- (void)payFailure{
    // 支付失败
    // [RMMFileManager MBProgressWith:dic[@"memo"] onView:self.view];
    _resultView.hidden = YES;
    _backView.hidden = NO;
    self.navigationItem.title = @"支付结果";
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:(UIBarButtonItemStylePlain) target:self action:nil];
}
- (void)doneButClick{
    if ([_objName isEqualToString:@"打赏"]) {
        [self.navigationController popViewControllerAnimated:YES];
    } else  {
        [self.navigationController popToRootViewControllerAnimated:YES];
    }
}
- (void)backHomeButClick:(UIButton *)button{
    if (button == _backView.backHomeBut) {
        NS_POST(@"SHOPFRESH", nil, nil);
        [self.navigationController popToRootViewControllerAnimated:YES];
    } else {
        if ([_objName isEqualToString:@"打赏"]){
            [self beginPay];
        } else {
            [self confirmPay];
        }
    }
}
// applepay
//- (void)applePay{
//    if (![PKPaymentAuthorizationViewController class]) {
//        //PKPaymentAuthorizationViewController需iOS8.0以上支持
//        NSLog(@"操作系统不支持ApplePay，请升级至9.0以上版本，且iPhone6以上设备才支持");
//        return;
//    }
//    //检查当前设备是否可以支付
//    if (![PKPaymentAuthorizationViewController canMakePayments]) {
//        //支付需iOS9.0以上支持
//        NSLog(@"设备不支持ApplePay，请升级至9.0以上版本，且iPhone6以上设备才支持");
//        return;
//    }
//    //检查用户是否可进行某种卡的支付，是否支持Amex、MasterCard、Visa与银联四种卡，根据自己项目的需要进行检测
//    NSArray *supportedNetworks = @[PKPaymentNetworkAmex, PKPaymentNetworkMasterCard,PKPaymentNetworkVisa,PKPaymentNetworkChinaUnionPay];
//    if (![PKPaymentAuthorizationViewController canMakePaymentsUsingNetworks:supportedNetworks]) {
//        NSLog(@"没有绑定支付卡");
//        return;
//    }
//    NSLog(@"可以支付，开始建立支付请求");
//    //设置币种、国家码及merchant标识符等基本信息
//    PKPaymentRequest *payRequest = [[PKPaymentRequest alloc]init];
//    payRequest.countryCode = @"CN";     //国家代码
//    payRequest.currencyCode = @"CNY";       //RMB的币种代码
//    payRequest.merchantIdentifier = @"merchant.ApplePayDemoYasin";  //申请的merchantID
//    payRequest.supportedNetworks = supportedNetworks;   //用户可进行支付的银行卡
//    payRequest.merchantCapabilities = PKMerchantCapability3DS|PKMerchantCapabilityEMV;      //设置支持的交易处理协议，3DS必须支持，EMV为可选，目前国内的话还是使用两者吧
//    //    payRequest.requiredBillingAddressFields = PKAddressFieldEmail;
//    //如果需要邮寄账单可以选择进行设置，默认PKAddressFieldNone(不邮寄账单)
//    //楼主感觉账单邮寄地址可以事先让用户选择是否需要，否则会增加客户的输入麻烦度，体验不好，
//    payRequest.requiredShippingAddressFields = PKAddressFieldPostalAddress|PKAddressFieldPhone|PKAddressFieldName;
//    //送货地址信息，这里设置需要地址和联系方式和姓名，如果需要进行设置，默认PKAddressFieldNone(没有送货地址)
//    //
//    //设置两种配送方式
//    PKShippingMethod *freeShipping = [PKShippingMethod summaryItemWithLabel:@"包邮" amount:[NSDecimalNumber zero]];
//    freeShipping.identifier = @"freeshipping";
//    freeShipping.detail = @"6-8 天 送达";
//    
//    PKShippingMethod *expressShipping = [PKShippingMethod summaryItemWithLabel:@"极速送达" amount:[NSDecimalNumber decimalNumberWithString:@"10.00"]];
//    expressShipping.identifier = @"expressshipping";
//    expressShipping.detail = @"2-3 小时 送达";
//    shippingMethods = [NSMutableArray arrayWithArray:@[freeShipping, expressShipping]];
//    //shippingMethods为配送方式列表，类型是 NSMutableArray，这里设置成成员变量，在后续的代理回调中可以进行配送方式的调整。
//    payRequest.shippingMethods = shippingMethods;
//        
//    NSDecimalNumber *subtotalAmount = [NSDecimalNumber decimalNumberWithMantissa:1275 exponent:-2 isNegative:NO];   //12.75
//    PKPaymentSummaryItem *subtotal = [PKPaymentSummaryItem summaryItemWithLabel:@"商品价格" amount:subtotalAmount];
//    
//    NSDecimalNumber *discountAmount = [NSDecimalNumber decimalNumberWithString:@"-12.74"];      //-12.74
//    PKPaymentSummaryItem *discount = [PKPaymentSummaryItem summaryItemWithLabel:@"优惠折扣" amount:discountAmount];
//    
//    NSDecimalNumber *methodsAmount = [NSDecimalNumber zero];
//    PKPaymentSummaryItem *methods = [PKPaymentSummaryItem summaryItemWithLabel:@"包邮" amount:methodsAmount];
//    
//    NSDecimalNumber *totalAmount = [NSDecimalNumber zero];
//    totalAmount = [totalAmount decimalNumberByAdding:subtotalAmount];
//    totalAmount = [totalAmount decimalNumberByAdding:discountAmount];
//    totalAmount = [totalAmount decimalNumberByAdding:methodsAmount];
//    PKPaymentSummaryItem *total = [PKPaymentSummaryItem summaryItemWithLabel:@"Yasin" amount:totalAmount];  //最后这个是支付给谁。哈哈，快支付给我
//    
//    summaryItems = [NSMutableArray arrayWithArray:@[subtotal, discount, methods, total]];
//    //summaryItems为账单列表，类型是 NSMutableArray，这里设置成成员变量，在后续的代理回调中可以进行支付金额的调整。
//    payRequest.paymentSummaryItems = summaryItems;
//    
//    
//    //ApplePay控件
//    PKPaymentAuthorizationViewController *view = [[PKPaymentAuthorizationViewController alloc]initWithPaymentRequest:payRequest];
//    view.delegate = self;
//    [self presentViewController:view animated:YES completion:nil];
//}
//#pragma mark - PKPaymentAuthorizationViewControllerDelegate
//- (void)paymentAuthorizationViewController:(PKPaymentAuthorizationViewController *)controller
//                  didSelectShippingContact:(PKContact *)contact
//                                completion:(void (^)(PKPaymentAuthorizationStatus, NSArray<PKShippingMethod *> * _Nonnull, NSArray<PKPaymentSummaryItem *> * _Nonnull))completion{
//    //contact送货地址信息，PKContact类型
//    NSPersonNameComponents *name = contact.name;                //联系人姓名
//    CNPostalAddress *postalAddress = contact.postalAddress;     //联系人地址
//    NSString *emailAddress = contact.emailAddress;              //联系人邮箱
//    CNPhoneNumber *phoneNumber = contact.phoneNumber;           //联系人手机
//    NSString *supplementarySubLocality = contact.supplementarySubLocality;  //补充信息,iOS9.2及以上才有
//    
//    //送货信息选择回调，如果需要根据送货地址调整送货方式，比如普通地区包邮+极速配送，偏远地区只有付费普通配送，进行支付金额重新计算，可以实现该代理，返回给系统：shippingMethods配送方式，summaryItems账单列表，如果不支持该送货信息返回想要的PKPaymentAuthorizationStatus
//    completion(PKPaymentAuthorizationStatusSuccess, shippingMethods, summaryItems);
//}
//
//- (void)paymentAuthorizationViewController:(PKPaymentAuthorizationViewController *)controller
//                   didSelectShippingMethod:(PKShippingMethod *)shippingMethod
//                                completion:(void (^)(PKPaymentAuthorizationStatus, NSArray<PKPaymentSummaryItem *> * _Nonnull))completion{
//    //配送方式回调，如果需要根据不同的送货方式进行支付金额的调整，比如包邮和付费加速配送，可以实现该代理
//    PKShippingMethod *oldShippingMethod = [summaryItems objectAtIndex:2];
//    PKPaymentSummaryItem *total = [summaryItems lastObject];
//    total.amount = [total.amount decimalNumberBySubtracting:oldShippingMethod.amount];
//    total.amount = [total.amount decimalNumberByAdding:shippingMethod.amount];
//    
//    [summaryItems replaceObjectAtIndex:2 withObject:shippingMethod];
//    [summaryItems replaceObjectAtIndex:3 withObject:total];
//    
//    completion(PKPaymentAuthorizationStatusSuccess, summaryItems);
//}
//-(void)paymentAuthorizationViewController:(PKPaymentAuthorizationViewController *)controller didSelectPaymentMethod:(PKPaymentMethod *)paymentMethod completion:(void (^)(NSArray<PKPaymentSummaryItem *> * _Nonnull))completion{
//    //支付银行卡回调，如果需要根据不同的银行调整付费金额，可以实现该代理
//    completion(summaryItems);
//}
//-(void)paymentAuthorizationViewController:(PKPaymentAuthorizationViewController *)controller didSelectShippingAddress:(ABRecordRef)address completion:(void (^)(PKPaymentAuthorizationStatus, NSArray<PKShippingMethod *> * _Nonnull, NSArray<PKPaymentSummaryItem *> * _Nonnull))completion{
//    //送货地址回调，已弃用
//}
//- (void)paymentAuthorizationViewController:(PKPaymentAuthorizationViewController *)controller
//                       didAuthorizePayment:(PKPayment *)payment
//                                completion:(void (^)(PKPaymentAuthorizationStatus status))completion {
//    
//    PKPaymentToken *payToken = payment.token;
//    //支付凭据，发给服务端进行验证支付是否真实有效
//    PKContact *billingContact = payment.billingContact;     //账单信息
//    PKContact *shippingContact = payment.shippingContact;   //送货信息
//    PKContact *shippingMethod = payment.shippingMethod;     //送货方式
//    //等待服务器返回结果后再进行系统block调用
//    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//        //模拟服务器通信
//        completion(PKPaymentAuthorizationStatusSuccess);
//    });
//    
//    
//}
//- (void)paymentAuthorizationViewControllerDidFinish:(PKPaymentAuthorizationViewController *)controller{
//    [controller dismissViewControllerAnimated:YES completion:nil];
//}
- (CGFloat)getToatalPriceWithArray:(NSArray *)array{
    CGFloat totalPrcie = 0.00;
    for (RMMShopingModel *model in array) {
        if ([model.isSelect isEqualToString:@"1"]) {
            CGFloat prcie = [model.PRICE floatValue];
            NSInteger count = [model.COUNT integerValue];
            totalPrcie += prcie * count;
        }
    }
    return totalPrcie;
}
- (void)getRedBagTitle{
    [OSRequestManager requestWithUrlString:GetRedBagTitleUrl parDic:nil method:GET finish:^(NSDictionary *dataDic) {
        NSString *status = [NSString stringWithFormat:@"%@",dataDic[@"status"]];
        if ([status isEqualToString:@"1"]) {
            _moneyShareView.hidden = NO;
            NSDictionary *dic = [RMMFileManager setValueForDic:dataDic[@"data"]];
            _titleName = dic[@"RED_BAG_TITLE"];
            _desTitleName = dic[@"RED_BAG_BODY"];
        }
    } error:^(NSError *errors) {
        
    } view:self.view];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
